const multer = require('multer');
const path = require('path');
const { getFileUrl } = require('../utils/fileHelper');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/');
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

const fileFilter = (req, file, cb) => {
  const allowedTypes = ['image/jpeg', 'image/png'];
  if (!allowedTypes.includes(file.mimetype)) {
    return cb(new Error('仅支持 JPEG 和 PNG 格式的图片'), false);
  }
  cb(null, true);
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: { fileSize: 1024 * 1024 * 5 } // 限制文件大小为 5MB
});

// 添加处理文件URL的中间件
upload.processFileUrls = (req, res, next) => {
  if (req.file) {
    req.file.url = getFileUrl(req.file.path);
  }
  if (req.files) {
    Object.keys(req.files).forEach(key => {
      req.files[key] = req.files[key].map(file => ({
        ...file,
        url: getFileUrl(file.path)
      }));
    });
  }
  next();
};

module.exports = upload; 